<template>
	<div class="app-container">
		<div ref="box1" class="flex-center margin-bottom-10">
			<span class="el-icon-menu menu-title-icon"></span>
			<el-cascader
				ref="tree"
				v-model="menuVal"
				size="large"
				:options="menuList"
				style="width: 260px"
				placeholder="菜单"
				:props="{
					value: 'id',
					label: 'name'
				}"
				@change="onMenuChange"
			></el-cascader>
		</div>

		<jk-card>
			<div ref="box2" class="margin-bottom-10 flex-between-center">
				<div class="flex-start-center">
					<el-radio-group v-model="tabActive" :class="tabList.length ? 'item-gap' : ''" @change="onRadioChange">
						<el-radio-button
							v-for="(item, index) in tabList"
							:key="index"
							:label="index + ''"
							:disabled="!menuVal.length"
						>
							<span>{{ item.name }}</span>
							<el-popover
								title="编辑"
								placement="bottom"
								trigger="hover"
							>
								<div class="flex-start-center margin-bottom-10">
									<el-tag type="info" size="large" class="item-gap">编号</el-tag>
									<jk-input v-model="item.code" size="small"></jk-input>
								</div>
								<div class="flex-start-center">
									<el-tag type="info" size="large" class="item-gap">名称</el-tag>
									<jk-input v-model="item.name" size="small"></jk-input>
								</div>
								<div class="flex-center margin-top-10">
									<el-button icon="el-icon-delete" type="danger" size="small" class="item-gap" @click="onRemoveTabItem(index)">移除</el-button>
								</div>
								<div slot="reference" class="el-icon-edit edit-tab-icon"></div>
							</el-popover>
						</el-radio-button>
					</el-radio-group>
					<el-button :disabled="!menuVal.length" icon="el-icon-plus" @click="onAddTab"></el-button>
				</div>
				<div class="flex-end-center-wrap">
					<div class="item-gap cp-btn"><el-button ref="cpBtn" :disabled="!menuVal.length || !tabList.length" size="small" @click="onCopyBtn(0)">复制</el-button></div>
					<el-popover title="提示" width="800" placement="bottom" @hide="clipboardVal = ''">
						<div>
							<el-input v-model="clipboardVal" placeholder="粘贴" type="textarea" :rows="8"></el-input>
						</div>
						<div class="flex-center margin-top-10">
							<el-button type="error" size="mini" @click="clipboardVal = ''">清空</el-button>
							<el-button type="primary" size="mini" @click="onCopyBtn(1)">解析</el-button>
						</div>
						<div slot="reference" class="item-gap"><el-button :disabled="!menuVal.length || !tabList.length" size="small">粘贴</el-button></div>
					</el-popover>
					<el-button :disabled="!menuVal.length || !tabList.length" size="small" icon="el-icon-orange" class="item-gap" @click="onInitBtn">模板</el-button>
					<div class="item-gap"><el-button size="small" :disabled="!menuVal.length" :loading="refreshBtnLoading" type="primary" icon="el-icon-refresh" circle @click="onRefreshBtn"></el-button></div>
					<el-popover v-model="showFullReleasePopover" title="提示" width="300" placement="bottom">
						<p>全量发布，会初始化所有用户的所有菜单配置，确认操作吗？</p>
						<div class="flex-end-center">
							<el-button size="mini" type="danger" @click="showFullReleasePopover = false">取消</el-button>
							<el-button type="primary" size="mini" :loading="fullReleaseBtnLoading" @click="onFullReleaseBtn">确定</el-button>
						</div>
						<div slot="reference" class="item-gap"><el-button size="small" type="primary" icon="el-icon-s-promotion">全量发布</el-button></div>
					</el-popover>
					<el-popover v-model="showPartReleasePopover" title="提示" width="300" placement="bottom">
						<p>灰度发布，会初始化所有用户在当前菜单的配置，确认操作吗？</p>
						<div class="flex-end-center">
							<el-button size="mini" type="danger" @click="showPartReleasePopover = false">取消</el-button>
							<el-button type="primary" size="mini" :loading="partReleaseBtnLoading" @click="onPartReleaseBtn">确定</el-button>
						</div>
						<div slot="reference" class="item-gap"><el-button :disabled="!menuVal.length || !tabList.length" size="small" type="info" icon="el-icon-upload">灰度发布</el-button></div>
					</el-popover>
					<el-button :disabled="!menuVal.length || !tabList.length" :loading="saveBtnLoading" size="small" type="primary" icon="el-icon-finished" @click="onSaveBtn">保存</el-button>
				</div>
			</div>
			<jk-table ref="xTable" border row-key :height="tableHeight + 6" :highlight-hover-row="true" size="mini" class="sortable-row-demo" :scroll-y="{enabled: false}" :data="tableData">
				<vxe-column width="60" align="center">
					<template #default>
						<div class="drag-btn"><i class="el-icon-rank"></i></div>
					</template>
					<template #header>
						<el-popover title="提示" content="双击拖动调整顺序！" placement="bottom" trigger="hover">
							<i slot="reference" class="el-icon-info drag-info-icon"></i>
						</el-popover>
					</template>
				</vxe-column>
				<vxe-column field="operation" title="操作" width="120" align="center">
					<template slot-scope="scope">
						<div class="flex-center">
							<div class="item-gap"><el-button size="mini" icon="el-icon-plus" @click="onAddButton(scope)" /></div>
							<div><el-button icon="el-icon-minus" size="mini" @click="onReduceButton(scope)" /></div>
						</div>
					</template>
				</vxe-column>
				<vxe-column field="title" title="列名" min-width="130">
					<template slot-scope="scope">
						<el-input v-model="scope.row.title" size="mini" />
					</template>
				</vxe-column>
				<vxe-column field="keyName" title="key" min-width="160">
					<template slot-scope="scope">
						<el-input v-model="scope.row.keyName" size="mini" />
					</template>
				</vxe-column>
				<vxe-column field="align" title="对齐方式" width="110">
					<template slot-scope="scope">
						<el-select v-model="scope.row.align" placeholder="对齐方式" size="mini">
							<el-option v-for="item in alignOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</template>
				</vxe-column>
				<vxe-column field="fixed" title="固定" width="120" align="left">
					<template slot-scope="scope">
						<el-select v-model="scope.row.fixed" placeholder="固定方向" class="width-100-percent" size="mini">
							<el-option v-for="item in fixedOptions" :key="item.id" :label="item.name" :value="item.id"></el-option>
						</el-select>
					</template>
				</vxe-column>
				<vxe-column field="width" title="列宽" width="120" align="right">
					<template slot-scope="scope">
						<el-input-number v-model="scope.row.width" :min="0" class="width-100-percent" size="mini" controls-position="right" />
					</template>
				</vxe-column>
				<vxe-column field="minWidth" title="最小列宽" width="120" align="right">
					<template slot-scope="scope">
						<el-input-number v-model="scope.row.minWidth" :min="0" class="width-100-percent" size="mini" controls-position="right" />
					</template>
				</vxe-column>
				<vxe-column field="sortable" title="排序" width="100" align="center">
					<template slot-scope="scope">
						<el-checkbox v-model="scope.row.sortable" size="mini" style="transform: scale(.9)">是</el-checkbox>
					</template>
				</vxe-column>
				<vxe-column field="ifShow" title="显示" width="90" align="center" fixed="right">
					<template slot-scope="scope">
						<el-switch v-model="scope.row.ifShow"></el-switch>
					</template>
				</vxe-column>
			</jk-table>
		</jk-card>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar } from '/src/utils/jk/jk-tool';
    import {
        systemColumnConfigGet, systemColumnConfigPublish, systemColumnConfigPublishPage, systemColumnConfigUpdate
    } from '../../../api/system/column-config';
    import Sortable from 'sortablejs';
    import uploadExcelComponent from '../../../components/UploadExcel/index.vue';
    import exportAndImport from './export-and-import';
    import { systemAuthListLeftMenus } from '../../../api/menu';
    import Clipboard from 'clipboard';
    export default {
        components: {
            uploadExcelComponent
        },
        mixins: [calHeight, exportAndImport],
        data() {
            return {
                shortcutData: [
                    { title: '编号', sortNum: 1, keyName: 'code', align: 'left', width: 0, minWidth: 100, sortable: false, fixed: '', ifShow: true },
                    { title: '名称', sortNum: 1, keyName: 'name', align: 'left', width: 0, minWidth: 100, sortable: false, fixed: '', ifShow: true },
                    { title: '创建人', sortNum: 1, keyName: 'creatorName', align: 'left', width: 100, minWidth: 0, sortable: false, fixed: '', ifShow: true },
                    { title: '创建时间', sortNum: 1, keyName: 'createTime', align: 'left', width: 160, minWidth: 0, sortable: false, fixed: '', ifShow: true },
                    { title: '修改人', sortNum: 1, keyName: 'updaterName', align: 'left', width: 100, minWidth: 0, sortable: false, fixed: '', ifShow: true },
                    { title: '修改时间', sortNum: 1, keyName: 'updateTime', align: 'left', width: 160, minWidth: 0, sortable: false, fixed: '', ifShow: true },
                    { title: '状态', sortNum: 1, keyName: 'auditState', align: 'center', width: 100, minWidth: 0, sortable: false, fixed: '', ifShow: true }
                ],
                partReleaseBtnLoading: false,
                showPartReleasePopover: false,
                showFullReleasePopover: false,
                refreshBtnLoading: false,
                fullReleaseBtnLoading: false,
                sortable1: null,
                menuPath: '',
                editTabIdx: null,
                tabList: [],
                saveBtnLoading: false,
                exportLoading: false,
                tabActive: '1',
                menuVal: [],
                menuList: [],
                saveDialogState: false,
                tableLoading: false,
                tableData: [],
                searchParams: {
                    count: 0,
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    nameOrCode: '',
                    workshopId: null,
                    processId: null,
                    status: null,
                    deviceModelId: null,
                    deviceCategoryId: null
                },
                clipboardVal: ''
            };
        },
        mounted() {
            this.loadSortTable();
            this.getDependentData();
        },
        methods: {
            onCopyBtn(type) {
                if (!type) {
                    const clipboard = new Clipboard('.cp-btn', {
                        text: () => JSON.stringify(this.tableData)
                    });
                    clipboard.on('success', () => {
                        tipsBar(this, 'custom', 'success', '复制成功！');
                    });
                    clipboard.on('error', () => {
                        // 可以添加失败的回调
                    });
                } else {
                    try {
                        const jsonData = this.clipboardVal ? JSON.parse(this.clipboardVal) : [];
                        if (Array.isArray(jsonData)) {
                            this.tableData = jsonData;
                        } else {
                            tipsBar(this, 'custom', 'warning', '格式错误！');
                        }
                    } catch (err) {
                        tipsBar(this, 'custom', 'warning', '格式错误！');
                    }
                }
            },
            onInitBtn() {
                this.tableData = JSON.parse(JSON.stringify(this.shortcutData));
            },
            onRemoveTabItem(idx) {
                this.tabList.splice(idx, 1);
                this.tabActive = '';
                this.tableData = [];
            },
            onRefreshBtn() {
                this.tabList = [];
                this.tableData = [];
                this.refreshBtnLoading = true;
                this.getMenuColumnListRequest();
            },
            onPartReleaseBtn() {
                this.partReleaseBtnLoading = true;
                return systemColumnConfigPublishPage({ platform: this.platform, menuId: this.menuVal[this.menuVal.length - 1] }).then(res => {
                    this.partReleaseBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'custom', 'success', '灰度发布成功！');
                        this.showPartReleasePopover = false;
                        this.getMenuColumnListRequest();
                    }
                });
            },
            onFullReleaseBtn() {
                this.fullReleaseBtnLoading = true;
                return systemColumnConfigPublish({}, { platform: this.platform }).then(res => {
                    this.fullReleaseBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'custom', 'success', '全量发布成功！');
                        this.showFullReleasePopover = false;
                        this.getMenuColumnListRequest();
                    }
                });
            },
            onSaveBtn() {
                /**
             * 保存的逻辑：
             1.保存配置数据（更新配置表）

             2.如果列名ID不存在
             2.1如果，列名状态为“显示”，根据菜单ID,去“用户配置表”，将该列名添加进去（不存在的情况下）

             3.如果列名ID存在
             3.1如果，列名状态为“隐藏”，那关联“用户配置表”把这个列名ID的配置删掉
             3.2如果，列名状态为“显示”，根据菜单ID,去“用户配置表”，将该列名添加进去（不存在的情况下）
             * */
                this.saveRequest();
            },
            onAddButton(scope) {
                this.tableData.splice(scope.$rowIndex + 1, 0, JSON.parse(JSON.stringify(this.initColumnData())));
            },
            onReduceButton(scope) {
                if (this.tableData.length > 1) {
                    this.tableData.splice(scope.$rowIndex, 1);
                }
            },
            initTabItem() {
                return {
                    code: `Tab${this.tabList.length + 1}`,
                    name: `列表${this.tabList.length + 1}`,
                    itemList: [this.initColumnData()]
                };
            },
            onAddTab() {
                this.tabList.push(this.initTabItem());
            },
            initColumnData() {
                return { title: '', sortNum: 1, keyName: '', align: 'left', width: 0, minWidth: 100, sortable: false, fixed: '', filterType: -1, ifShow: true };
            },
            onRadioChange(idx) {
                this.editTabIdx = idx;
                if (this.tabList[idx].itemList.length) {
                    this.tableData = this.tabList[idx].itemList;
                } else {
                    this.tableData = [this.initColumnData()];
                }
            },
            saveRequest() {
                this.saveBtnLoading = true;
                return systemColumnConfigUpdate({
                    menuId: this.menuVal[this.menuVal.length - 1],
                    path: this.menuPath,
                    columnConfigList: this.tabList.map(x => {
                        x.itemList.forEach((k, index) => {
                            k.sortNum = index + 1;
                        });
                        return x;
                    })
                }).then(res => {
                    this.saveBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$tipsBar(this, 'save');
                        this.getMenuColumnListRequest();
                    }
                });
            },
            loadSortTable() {
                this.$nextTick(() => {
                    const xTable = this.$refs.xTable;
                    this.sortable1 = Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
                        handle: '.drag-btn',
                        animation: 500,
                        onEnd: ({ newIndex, oldIndex }) => {
                            const currRow = this.tableData.splice(oldIndex, 1)[0];
                            this.tableData.splice(newIndex, 0, currRow);
                        }
                    });
                });
            },
            getMeuListRequest() {
                return systemAuthListLeftMenus().then(res => {
                    if (res.data.status === 200) {
                        this.menuList = res.data.res;
                    }
                });
            },
            onMenuChange(e) {
                this.tableData = [];
                this.menuPath = this.$refs.tree.getCheckedNodes()[0].data.path;
                this.tabActive = '';
                if (e.length) {
                    this.getMenuColumnListRequest();
                } else {
                    this.menuList = [];
                }
            },
            getMenuColumnListRequest() {
                if (this.menuVal.length) {
                    this.tableLoading = true;
                    return systemColumnConfigGet({ state: 1, path: this.menuPath }).then(res => {
                        // return systemColumnConfigGet({ state: 1, menuId: this.menuVal[this.menuVal.length - 1] }).then(res => {
                        this.tableLoading = false;
                        this.refreshBtnLoading = false;
                        if (res.data.status === 200) {
                            this.tabList = res.data.res.columnConfigList;
                            if (res.data.res.columnConfigList && res.data.res.columnConfigList.length) {
                                this.tableData = res.data.res.columnConfigList[0].itemList;
                                this.tabActive = '0';
                                this.editTabIdx = 0;
                            } else {
                                this.tableData = [];
                            }
                        }
                    });
                } else {
                    this.refreshBtnLoading = false;
                }
            },
            async getDependentData() {
                await this.getMeuListRequest();
            }
        },
        watch: {
            tableData: {
                handler(newVal) {
                    if (newVal && newVal.length) this.$set(this.tabList[this.editTabIdx], 'itemList', JSON.parse(JSON.stringify(newVal)));
                },
                deep: true
            }
        }
    };
</script>
<style scoped lang="scss">
  .menu-title-icon {
    font-size: 29px;
    color: #909399;
    margin-right: 4px;
  }
    .edit-tab-icon {
        margin-left: 8px;
        font-size: 13px;
    }
    .edit-tab-icon:hover {
        cursor: pointer;
    }
    .drag-info-icon {
        font-size: 14px;
    }
    .drag-btn {
        cursor: move;
        color: #2d8cf0;
        transition: all .5s;
        font-size: 18px;
    }
    .drag-btn:hover {
        transform: rotate(90deg);
    }
</style>
